package com.dys.dao.impl;

import com.dys.dao.PersonDAO;
import com.dys.entity.Person;
import com.dys.rowmapper.impl.PersonRowMapper;
import com.dys.util.DaoDruidUtil;

import java.sql.SQLException;
import java.util.List;

/**
 * @className: com.dys.dao.impl.PersonDaoImpl
 * @description: 实现PersonDao接口，实现内5个方法
 * @author: pine cone
 * @version: v1.0.0
 * @createTime: 2024/09/12 下午10:52
 */
public class PersonDaoImpl03 implements PersonDAO {
    private final DaoDruidUtil<Person> daoDruidUtil = new DaoDruidUtil<>();

    @Override
    public int insert(Person person) throws SQLException {
        // 1、编写SQL语句
        String sql = "insert into person(name, age,date_of_birth,email,address) values(?,?,?,?,?)";

        // 2、调用DaoUtils
        int count = daoDruidUtil.commonUpdate(sql, person.getName(), person.getAge(), person.getDateOfBirth(), person.getEmail(), person.getAddress());

        // 2、返回结果
        return count;
    }

    @Override
    public int updateById(Person person) throws SQLException {
        // 1、编写SQL语句
        String sql = "update person set name =?,age=? where id=?";

        // 2、调用DaoUtils
        int count = daoDruidUtil.commonUpdate(sql, person.getName(), person.getAge(), person.getId());

        // 3、返回结果
        return count;
    }

    @Override
    public int deleteById(int id) throws SQLException {
        // 1、编写SQL语句
        String sql = "delete from person where id=?";

        // 2、调用DaoUtils
        int count = daoDruidUtil.commonUpdate(sql, id);

        // 3、返回结果
        return count;
    }

    @Override
    public Person findById(int id) throws SQLException {
        // 1、编写SQL语句
        String sql = "select * from person where id=?";

        // 2、调用DaoUtils
        List<Person> list = daoDruidUtil.commonSelect(sql, new PersonRowMapper(), id);

        // 3、返回结果
        return list != null && !list.isEmpty() ? list.get(0) : null;
    }

    @Override
    public List<Person> findAll() throws SQLException {
        // 1、编写SQL语句
        String sql = "select * from person";

        // 2、调用DaoUtils
        List<Person> list = daoDruidUtil.commonSelect(sql, new PersonRowMapper());

        // 3、返回结果
        return list;
    }
}
